package com.yz.controller;

import com.yz.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${fileUpload.basePath}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file){
        //生成一个新的文件名
        String originalFileName = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        //文件保存位置
        File file1 = new File(basePath);
        //  如果文件夹不存在 创建文件夹
        if (!file1.exists())
            file1.mkdirs();
        //保存文件
        try {
            file.transferTo(new File(basePath+filename+suffix));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("originalFileName:"+originalFileName);
        log.info("newFilename:"+filename + suffix);
        return R.success(filename + suffix);
    }

    /**
     * 文件下载
     * @param response
     * @param name
     * @return
     */
    @RequestMapping("/download")
    public R<String> download(HttpServletResponse response, String name){
        //读取文件输出文件
        try {
            File file = new File(basePath+name);
            if (!file.exists())
                return R.error("文件不存在");
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream writer = response.getOutputStream();

            int len = 0;
            byte[] b = new byte[1024];
            while ((len = fileInputStream.read(b))!= -1){
                writer.write(b,0,len);
                writer.flush();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success("成功");
    }
}
